//
//  UserManager.m
//  NiubilityProject
//
//  Created by Apple on 2017/11/17.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "UserManager.h"
#import "JSCountryInfoModel.h"

@implementation UserManager
SINGLETON_FOR_CLASS(UserManager);
-(instancetype)init{
    self = [super init];
    if (self) {
        //被踢下线
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onKick)
                                                     name:KNotificationOnKick
                                                   object:nil];
    }
    return self;
}
/**
 三方登录
 
 @param loginType 登录方式
 @param completion 回调
 */
-(void)login:(UserLoginType )loginType completion:(loginBlock)completion{
    
}
/**
 三方登录
 
 @param noti 通知
 */
-(void)onKick:(NSNotification *)noti{
    
}
/**
 带参登录
 
 @param loginType 登录方式
 @param params 参数，手机和账号登录需要
 @param completion 回调
 */
-(void)login:(UserLoginType )loginType params:(NSDictionary *)params completion:(loginBlock)completion{
    self.loginType = loginType;
    if (loginType == kUserLoginTypeQQ) {

    }else if (loginType == kUserLoginTypeWeChat){

    }else if(loginType == kUserLoginTypeFaceBook){

    }else{
        // Unknown..
    }
    // 第三方登录
    if (loginType != kUserLoginTypePwd) {
        
    }else{ /// 账号密码登录
        [[JSAlertHelper sharedInstance] showLoadingText:JSLocalizedString(@"loginmarch") inView:nil animation:YES];
        [JSNetManager js_courrentProjectRequestWithMouth:@"login" cache:NO ifShowFinishStatu:NO parameters:params.mutableCopy successBlock:^(id response) {
            [self LoginSuccess:response completion:completion];
        } failureBlock:^(NSError *error) {
            if (completion) {
                completion(NO,@"登录返回数据异常");
            }
            KPostNotification(KNotificationLoginStateChange, @NO);
        }];
    }
}
#pragma mark ————— 登录成功处理 —————
-(void)LoginSuccess:(id )responseObject completion:(loginBlock)completion{
    if (ValidDict(responseObject)) {
        if ([responseObject[@"status"] integerValue] == 90001) {
            if (completion) {
                completion(NO,@"90001");
            }
            KPostNotification(KNotificationLoginStateChange, @NO);
            return;
        }
        if (ValidDict(responseObject[@"data"])) {
            NSDictionary *data = responseObject[@"data"];
            self.curUserInfo = [UserInfo mj_objectWithKeyValues:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                [JSAlertHelper showSucceedHideAfterDelay:2 text:JSLocalizedString(@"loginSource") inView:nil animation:YES];
            });
            [self.curUserInfo save];
            self.isLogined   = YES;
            KPostNotification(KNotificationLoginStateChange, @YES);
            if (completion) {
                completion(YES,nil);
            }
            JSLog(@"%@", data);
            }else{
                if (completion) {
                    completion(NO,@"登录返回数据异常");
                }
                KPostNotification(KNotificationLoginStateChange, @NO);
            }
    }else{
        if (completion) {
            completion(NO,@"登录返回数据异常");
        }
        KPostNotification(KNotificationLoginStateChange, @NO);
    }
    
}
/**
 连接融云
 

 */
-(void)connectRCloud{
    [[RCIM sharedRCIM] connectWithToken:self.curUserInfo.ry_token success:^(NSString *userId) {
        JSLog(@"\n-----------------\n融云链接成功\n--------------\n");
        [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
        RCUserInfo *info = [[RCUserInfo alloc] init];
        info.name = self.curUserInfo.username;
        info.userId = self.curUserInfo.userid;
        info.portraitUri = self.curUserInfo.avatar;
        [RCIM sharedRCIM].currentUserInfo = info;
        [JSRCloudModel updaeOrSave:info];
    } error:^(RCConnectErrorCode status) {
        JSLog(@"登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        JSLog(@"token错误");
    }];
}
/**
 退出登录
 
 @param completion 回调
 */
- (void)logout:(loginBlock)completion{
    // 1.IM退出
    // 2.界面切换 -> 发送通知形式 通知外部
    // 3.删除用户数据
    if ([UserInfo clearTable]) {
        if (completion) {
            completion(YES,nil);
        }
    }
    KPostNotification(KNotificationLoginStateChange, @NO);
}
-(void)autoLoginToServer:(loginBlock)completion{
    NSDictionary *params = @{@"username":self.curUserInfo.email,@"password":self.curUserInfo.pass};
    // 自动登录
    [JSNetManager js_courrentProjectRequestWithMouth:@"login" cache:NO ifShowFinishStatu:NO parameters:params.mutableCopy successBlock:^(id response) {
        if (ValidDict(response)) {
            if (ValidDict(response[@"data"]) && [UserInfo clearTable]) {
                NSDictionary *data = response[@"data"];
                self.curUserInfo = [UserInfo mj_objectWithKeyValues:data];
                [self.curUserInfo save];
                self.isLogined   = YES;
                if (completion) {
                    completion(YES,nil);
                }
                JSLog(@"自动登录成功");
            }else{
                if (completion) {
                    completion(NO,@"登录返回数据异常 or 清楚本地缓存失败");
                }
            }
        }else{
            if (completion) {
                completion(NO,@"登录返回数据异常");
            }
        }
    } failureBlock:^(NSError *error) {
        if (completion) {
            completion(NO,@"登录返回数据异常");
        }
    }];
  
}
- (NSArray *)photos{
    return @[@"http://www.quanjing.com/image/2017index/lx1.png",@"http://mpic.tiankong.com/d67/453/d67453f450cf97c87f40389a82f37ca5/640.jpg@360h",@"http://www.quanjing.com/image/2017index/ms2.png",@"http://www.quanjing.com/image/2017index/mt5.jpg?v=1"];
}
/**
 加载缓存用户数据
 
 @return 是否成功
 */
-(BOOL)loadUserInfo{
    UserInfo *user = [UserInfo findByPK:1];
    if (user) {
        self.curUserInfo = user;
        return YES;
    }
    /// 默认去数据库第一个数据。如果没有取到 不管是否有其他用户信息 全部情况 保证只有一个用户数据
    [UserInfo clearTable];
    return NO;
}
+(void)uploadImage:(NSArray *)images progress:(void(^)(CGFloat))progress respons:(void(^)(id))respons failur:(void(^)(NSError *))errorBack{
    if (!images) {
        return;
    }
    [JSNetManager js_currentUploadImageWithUrlString:BASE_URL showLoadingView:nil method:@"uploadImgs" parameters:@{}.mutableCopy imageArray:images fileName:@"avatar" successBlock:^(id response) {
        JSLog(@"%@", response);
        if ([response[@"status"] integerValue] == 1) {
            if (respons) {
                respons(response[@"data"]);
            }
        }else{
            if (errorBack) {
                errorBack(nil);
            }
        }
    } failurBlock:^(NSError *error) {
        if (errorBack) {
            errorBack(error);
        }
//        [JSAlertHelper showFailHideAfterDelay:2 text:JSLocalizedString(kLocalizableServerError) inView:nil animation:YES];
    } upLoadProgress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        if (progress) {
            progress(bytesProgress / totalBytesProgress);
        }
    }];
}
- (void) updataUserInfo:(loginBlock)completion{
    [JSNetManager js_courrentProjectRequestWithMouth:@"personalInfo" cache:NO ifShowFinishStatu:NO parameters:@{@"token":userManager.curUserInfo.token}.mutableCopy successBlock:^(id response) {
        if([response[@"status"] integerValue] == 200){
            if ([UserInfo clearTable] && ValidDict(response[@"data"][@"user_info"])) {
                UserInfo *u = [UserInfo mj_objectWithKeyValues:response[@"data"][@"user_info"]];
                self.curUserInfo = u;
                if ([u save]) {
                    JSLog(@"\n\n更新用户模型成功\n\n");
                    if (completion) {
                        completion(YES,nil);
                    }
                }else{
                    JSLog(@"\n\n更新用户模型失败**删除本地缓存失败\n\n");
                    if (completion) {
                        completion(NO,@"更新用户模型失败**删除本地缓存失败");
                    }
                }
            }
        }else{
            JSLog(@"\n\n更新用户模型失败**网络请求失败\n\n");
            if (completion) {
                completion(NO,@"更新用户模型失败**网络请求失败");
            }
        }
    } failureBlock:nil];
}

- (void)getCity:(void(^)(id,int))responseData{
    [JSNetManager js_courrentProjectRequestWithMouth:@"getCity" cache:NO ifShowFinishStatu:NO parameters:@{}.mutableCopy successBlock:^(id response) {
        if ([response[@"status"] integerValue] == 200) {
            if (ValidArray(response[@"data"][@"list"])) {
                self.countryDataSource = [JSCountryInfoModel mj_objectArrayWithKeyValuesArray:response[@"data"][@"list"]];
            }
            
            if (responseData) {
                responseData(self.countryDataSource,200);
            }
        }else{
            if (responseData) {
                responseData(nil,201);
            }
        }
    } failureBlock:^(NSError *error) {
        if (responseData) {
            responseData(nil,201);
        }
    }];
}
@end
